package com.qttaudio.example;

import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.PowerManager;
import android.support.annotation.Nullable;
import android.support.v4.widget.PopupWindowCompat;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CompoundButton;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;

import com.qttaudio.example.adapter.RoomMsgAdapter;
import com.qttaudio.example.config.Config;
import com.qttaudio.example.data.MicSeatBean;
import com.qttaudio.example.dialog.MicNetworkPopupWindow;
import com.qttaudio.example.dialog.MicPopupWindow;
import com.qttaudio.example.utils.GlideUtil;
import com.qttaudio.example.utils.Mp3Player;
import com.qttaudio.example.utils.Utils;
import com.qttaudio.ios.demo.R;
import com.qttaudio.sdk.channel.AudioOutput;
import com.qttaudio.sdk.channel.ChannelEngine;
import com.qttaudio.sdk.channel.ChannelFactory;
import com.qttaudio.sdk.channel.ChannelObserver;
import com.qttaudio.sdk.channel.ChannelRole;
import com.qttaudio.sdk.channel.ChannelUser;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import static com.qttaudio.sdk.channel.ChannelRole.TALKER;

/**
 * Created by Administrator on 2019/7/15 0015.
 * 这个类演示了AudioChannel API的使用
 */

public class RoomActivity extends BaseAvtivity implements CompoundButton.OnCheckedChangeListener {
    private static String TAG = RoomActivity.class.getSimpleName();

    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.iv_setting)
    ImageView ivSetting;
    @BindView(R.id.gv_mic_list)
    GridView gvMicList;
    @BindView(R.id.rv_message_list)
    RecyclerView rvMessageList;
    @BindView(R.id.tv_music_playing)
    TextView tvMusicPlaying;
    @BindView(R.id.view_colse_setting)
    LinearLayout viewColseSetting;
    @BindView(R.id.sp_music)
    Spinner spMusic;
    @BindView(R.id.tb_lolita)
    ToggleButton tbLolita;
    @BindView(R.id.iv_record_start)
    ToggleButton ivRecordStart;
    @BindView(R.id.iv_record_file)
    ImageView ivRecordFile;
    @BindView(R.id.ll_setting)
    LinearLayout llSetting;
    @BindView(R.id.tb_bottom_no_voice)
    ToggleButton tbBottomNoVoice;
    @BindView(R.id.tb_bottom_no_mic)
    ToggleButton tbBottomNoMic;
    @BindView(R.id.tb_music_start)
    ToggleButton tbMusicStart;
    @BindView(R.id.iv_music_stop)
    ImageView ivMusicStop;
    @BindView(R.id.tb_music_start_two)
    ToggleButton tbMusicStartTwo;
    @BindView(R.id.iv_music_stop_two)
    ImageView ivMusicStopTwo;

    private int lines = 0;
    private ChannelObserverImpl channelObserver = null;
    private volatile int channelUserSize = 0;
    private long roomId = 0;
    private Map<Long, Boolean> talkerlist;
    private Set<Long> audiencelist;
    private Mp3Player mp3Player = new Mp3Player();
    public static long mUid = -1;
    public static int myRtt = -1;
    private ChannelEngine audioChannel = null;
    private int mySeatPosition = -1;
    private int mySeatPositionTmp = -1;
    private Map<Integer, MicSeatBean> micSeatDataList;
    private MicItemAdapter micItemAdapter;
    final String[] spinnerMusicItems = {"本地播放", "远程播放", "共享播放"};
    private List<String> msgList = new ArrayList<String>();
    private RoomMsgAdapter msgListAdapter;
    private MicNetworkPopupWindow micNetworkPopupWindow;
    private MicPopupWindow micPopupWindow;
    private Context context;
    private PowerManager.WakeLock wl;

    private ProgressDialog myProgressDialog;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room);
        ButterKnife.bind(this);
        initView();
        context = this;
        roomId = Long.parseLong(getIntent().getStringExtra("roomId"));
        if (mUid < 0) {
            mUid = new Random().nextInt(100000);
        }
        tvTitle.setText("房间: " + roomId);
        channelObserver = new ChannelObserverImpl();
        talkerlist = new HashMap<>();
        audiencelist = new HashSet<>();

        audioChannel = ChannelFactory.GetChannelInstance();
        audioChannel.setUid(mUid);
        audioChannel.setObserver(channelObserver);
        ChannelRole mRole = ChannelRole.TALKER;
        audioChannel.join(roomId, mRole);

        tbBottomNoVoice.setOnCheckedChangeListener(this);
        tbBottomNoMic.setOnCheckedChangeListener(this);
        ivRecordStart.setOnCheckedChangeListener(this);
        tbMusicStart.setOnCheckedChangeListener(this);
        tbMusicStartTwo.setOnCheckedChangeListener(this);
        tbLolita.setOnCheckedChangeListener(this);



        PowerManager pm = (PowerManager)RoomActivity.this.getSystemService(
                Context.POWER_SERVICE);
        wl = pm.newWakeLock(
                PowerManager.PARTIAL_WAKE_LOCK
                        | PowerManager.ON_AFTER_RELEASE,
                TAG);
        wl.acquire();//为了保证任务不被系统休眠打断，申请WakeLock
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        wl.release();//任务结束后释放，如果不写该句。则可以用wl.acquire(timeout)的方式把释放的工作交给系统。
        dismissProgressDialog();
        audioChannel.leave();
        mp3Player.stop();
    }


    private void initView() {
        setMicGroupView();
        setMusicSpiner();
        setMsgListView();
    }

    private void setMsgListView() {
        // 定义一个线性布局管理器
        LinearLayoutManager manager = new LinearLayoutManager(this);
        // 设置布局管理器
        rvMessageList.setLayoutManager(manager);
        // 设置adapter
        msgListAdapter = new RoomMsgAdapter(RoomActivity.this, msgList);
        rvMessageList.setAdapter(msgListAdapter);

    }

    /**
     * 添加文字消息
     *
     * @param msg
     */
    private void appendMsg(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (msg != null) {
                    SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
                    msgList.add(sdf.format(new Date()) + ", " + msg);
                }
                msgListAdapter.notifyDataSetChanged();
                if (msgList.size() > 0) {
                    rvMessageList.scrollToPosition(msgList.size() - 1);
                }
                tvTitle.setText("房间: " + roomId + "(" + channelUserSize + "人)");
            }
        });
    }

    /**
     * 刷新麦位信息
     */
    public void updateSeatView() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                micItemAdapter.notifyDataSetChanged();
            }
        });
    }

    /**
     * 上麦
     *
     * @param uid
     * @param mute
     * @param position
     */
    private void onTalker(long uid, Boolean mute, int position, ChannelUser channelUser) {
        MicSeatBean micSeatBean = new MicSeatBean();
        micSeatBean.setChannelUser(channelUser);
        micSeatBean.setUid(uid);
        if (uid == mUid) {
            micSeatBean.setUsername("我(" + uid + ")");
        } else {
            micSeatBean.setUsername("用户" + uid);
        }
        Log.i(TAG, "mute uid:" + uid + "  setMute:" + mute);
        micSeatBean.setMute(mute);
        if (position < 0) {
            for (int i = 0; i < Config.RoomSeatCount; i++) {
                if (micSeatDataList.get(i) == null) {
                    micSeatDataList.put(i, micSeatBean);
                    if (mUid == micSeatBean.getUid()) {
                        mySeatPosition = i;
                    }
                    break;
                }
            }
        } else if (position < Config.RoomSeatCount) {
            if (micSeatDataList.get(position) == null) {
                micSeatDataList.put(position, micSeatBean);
            } else {
                Toast.makeText(RoomActivity.this, "该麦上有人了", Toast.LENGTH_SHORT).show();
            }
        }
        updateSeatView();
    }


    /**
     * 下麦
     *
     * @param uid
     */
    public void wheatTalker(long uid) {
        for (Map.Entry<Integer, MicSeatBean> integerMicSeatBeanEntry : micSeatDataList.entrySet()) {
            if (integerMicSeatBeanEntry.getValue() != null && integerMicSeatBeanEntry.getValue().getUid() == uid) {
                micSeatDataList.remove(integerMicSeatBeanEntry.getKey());
                if (micPopupWindow != null && micPopupWindow.isShowing() && micPopupWindow.getPosition() == integerMicSeatBeanEntry.getKey()) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            micPopupWindow.dismiss();
                        }
                    });
                }
            }
        }
        updateSeatView();
    }


    /**
     * 修改静音状态(只是我不接收)
     *
     * @param uid
     * @param only_me_mute
     */
    public void updateTalkerMuteOnlyMe(long uid, boolean only_me_mute) {

        for (MicSeatBean integerMicSeatBeanEntry : micSeatDataList.values()) {
            if (integerMicSeatBeanEntry != null) {
                if (uid == integerMicSeatBeanEntry.getUid()) {
                    integerMicSeatBeanEntry.setOnly_me_mute(only_me_mute);
                    break;
                }
            }
        }
        updateSeatView();
    }

    /**
     * 修改他人静音状态（用户自己禁言，不在发音）
     *
     * @param uid
     * @param mute
     */
    public void updateTalkerMute(long uid, boolean mute, ChannelUser channelUser) {

        for (MicSeatBean integerMicSeatBeanEntry : micSeatDataList.values()) {
            if (integerMicSeatBeanEntry != null) {
                if (uid == integerMicSeatBeanEntry.getUid()) {
                    Log.i(TAG, "--mute uid:" + uid + "  setMute:" + mute);
                    integerMicSeatBeanEntry.setMute(mute);
                    if (channelUser != null) {
                        integerMicSeatBeanEntry.setChannelUser(channelUser);
                    }
                    break;
                }
            }
        }
        updateSeatView();
    }

    /**
     * 修改说话状态
     *
     * @param uid
     * @param isTalking
     */
    public void updateTalkertalking(long uid, boolean isTalking) {
        for (MicSeatBean integerMicSeatBeanEntry : micSeatDataList.values()) {
            if (integerMicSeatBeanEntry != null) {
                if (uid == integerMicSeatBeanEntry.getUid()) {
                    if (integerMicSeatBeanEntry.isSpeaking() != isTalking) {
                        integerMicSeatBeanEntry.setSpeaking(isTalking);
                        updateSeatView();
                    }
                    break;
                }
            }
        }

    }

    /**
     * 修改私聊状态
     *
     * @param uid
     * @param isPrevateChat
     */
    public void updatePrevateChat(long uid, boolean isPrevateChat) {
        for (MicSeatBean integerMicSeatBeanEntry : micSeatDataList.values()) {
            if (integerMicSeatBeanEntry != null) {
                if (uid == integerMicSeatBeanEntry.getUid()) {
                    if (integerMicSeatBeanEntry.isPrivate_chat() != isPrevateChat) {
                        integerMicSeatBeanEntry.setPrivate_chat(isPrevateChat);
                        updateSeatView();
                    }
                    break;
                }
            }
        }
    }


    private void updateAudienceList(long uid, boolean isJoin) {
        if (isJoin)
            audiencelist.add(uid);
        else
            audiencelist.remove(uid);
        String userString = "";
        for (Long tmp : audiencelist) {
            userString += tmp + "\n";
        }
        final String msg = userString;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                //todo:kxl
            }
        });
    }


    @Override
    public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
        switch (compoundButton.getId()) {
            case R.id.localPlayCheck:
                mp3Player.enableLocalPlay(b);
                break;
            case R.id.remotePlayCheck:
                mp3Player.enableRemotePlay(b);
                break;
            case R.id.tb_bottom_no_voice:
                if (b)
                    AudioOutput.routeAudioTo(AudioOutput.SPEAKER);
                else
                    AudioOutput.routeAudioTo(AudioOutput.HEADPHONE);
                break;
            case R.id.tb_bottom_no_mic:
                updateTalkerMute(mUid, b, null);
                Log.i(TAG, "mute me " + b);
                audioChannel.mute(mUid, b);
                break;
            case R.id.tb_music_start:
                if (compoundButton.isPressed()) {
                    if (b) {
                        mp3Player.setFile(Utils.copyFile(RoomActivity.this, "bmg.mp3"));
                        tbMusicStartTwo.setChecked(false);
                        mp3Player.start();
                        tvMusicPlaying.setVisibility(View.VISIBLE);
                    } else {
                        mp3Player.pause();
                        tvMusicPlaying.setVisibility(View.INVISIBLE);
                    }
                }
                break;
            case R.id.tb_music_start_two:
                if (compoundButton.isPressed()) {
                    if (b) {
                        mp3Player.setFile(Utils.copyFile(RoomActivity.this, "perfect.mp3"));
                        tbMusicStart.setChecked(false);
                        tvMusicPlaying.setVisibility(View.VISIBLE);
                        mp3Player.start();
                    } else {
                        tvMusicPlaying.setVisibility(View.INVISIBLE);
                        mp3Player.pause();
                    }
                }
                break;
            case R.id.iv_record_start:
                if (b) {
                    audioChannel.startRecord(Config.record_dir + "/" + getRecordFileName());
                } else {
                    audioChannel.stopRecord();
                }
                break;
            case R.id.tb_lolita:
                //TODO: 变声
                break;
        }
    }

    public void onButtonStopClicked() {
        mp3Player.stop();
        tvMusicPlaying.setVisibility(View.INVISIBLE);
        tbMusicStart.setChecked(false);
        tbMusicStartTwo.setChecked(false);
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            showExitRoomDialog();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void showExitRoomDialog() {
        Log.i(TAG, "showExitRoomDialog");
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("确定要退出房间吗？")
                .setCancelable(false)
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog,
                                                int id) {
                                audioChannel.leave();
                                finish();
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                dialog.dismiss();
                            }
                        });
        AlertDialog alert = builder.create();
        alert.show();
    }

    /**
     * 录音文件入口
     * 进入录音文件会先离开房间
     */
    public void onButtonPlayClicked() {
        audioChannel.leave();
        finish();
        Intent intent = new Intent();
        intent.setClass(this, RecordFileActivity.class);
        startActivity(intent);
    }

    /**
     * 获取一个简单的录音文件名，不要重复
     *
     * @return
     */
    public String getRecordFileName() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS");
        Date date = new Date(System.currentTimeMillis());
        String time = formatter.format(date);
        return time + ".wav";
    }


    public void dismissProgressDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (myProgressDialog != null && myProgressDialog.isShowing()) {
                    myProgressDialog.dismiss();
                }
            }
        });
    }

    public void showProgressDialog() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (myProgressDialog != null && myProgressDialog.isShowing()) {
                    return;
                }
                myProgressDialog = new ProgressDialog(RoomActivity.this);
                myProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);//转盘
                myProgressDialog.setCancelable(false);
                myProgressDialog.setCanceledOnTouchOutside(false);

                myProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                    @Override
                    public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
                            showExitRoomDialog();
                            return true;
                        }
                        return false;
                    }
                });
                myProgressDialog.setMessage("正在重连……");
                myProgressDialog.show();
            }
        });
    }

    public void resetData() {
        micSeatDataList.clear();
        channelUserSize = 0;
        mySeatPosition = -1;
        mySeatPositionTmp = -1;
    }


    /**
     * 语音通道的方法实现，监听
     */
    private class ChannelObserverImpl implements ChannelObserver {
        /**
         * 进入房间成功
         */
        @Override
        public void onJoinSuccess(long roomId, long uid, ChannelRole role) {
            Log.d("qtt_debug", "onJoinSuccess roomId:"+roomId+"  role:" + role+"  ");
            channelUserSize++;
            dismissProgressDialog();
            appendMsg("进入房间成功");
            if (role == TALKER)
                onTalker(mUid, false, -1, null);
            else
                updateAudienceList(mUid, true);
        }

        /**
         * 进入房间失败
         *
         * @param code
         * @param message
         */
        @Override
        public void onJoinFail(final int code, final String message) {
            Log.d("qtt_debug", "onJoinFail " + message);
            runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Toast.makeText(context, "code:" + code + ", detail:" + message, Toast.LENGTH_LONG).show();
                }
            });
            finish();
        }

        /**
         * 正在重连...
         */
        @Override
        public boolean onWaitReconnecting(int seconds) {
            Log.d("qtt_debug", "onWaitReconnecting " + seconds);
            resetData();
            showProgressDialog();
            return true;
        }

        /**
         * 网络连接断开
         */
        @Override
        public void onClose() {
            Log.d("qtt_debug", "onClose");
//            Toast.makeText(RoomActivity.this, "服务器连接断开,请重试", Toast.LENGTH_LONG).show();
            finish();
        }

        /**
         * 自己的说话状态
         *
         * @param talking
         */
        @Override
        public void onSelfTalking(int talking) {
            Log.d("qtt_debug", "onSelfTalking " + talking);
            updateTalkertalking(mUid, talking > 0);
        }

        /**
         * 他人加入
         *
         * @param user
         */
        @Override
        public void onOtherJoin(ChannelUser user) {
            Log.d("qtt_debug", "onOtherJoin " + user.getUid());
            channelUserSize++;
            appendMsg("用户" + user.getUid() + " 进入房间");
            if (user.getAudioRole() == TALKER)
                onTalker(user.getUid(), user.isMuted(), -1, user);
            else
                updateAudienceList(user.getUid(), true);
        }

        /**
         * 他人离开
         *
         * @param user
         */
        @Override
        public void onOtherLeave(ChannelUser user) {
            Log.d("qtt_debug", "onOtherLeave " + user.getUid());
            channelUserSize--;
            appendMsg("用户" + user.getUid() + " 离开房间");
//            updateTalkerList(user.getUid(), false, false, "");
            wheatTalker(user.getUid());
            updateAudienceList(user.getUid(), false);
        }

        /**
         * 他人的说话状态
         *
         * @param user
         * @param talking
         */
        @Override
        public void onOtherTalking(ChannelUser user, int talking) {
            Log.d("qtt_debug", "onOtherTalking " + user.getUid() + ", talking=" + talking);
//            appendMsg(user.getUid() + " 说话状态：" + talking + "\n");
            updateTalkertalking(user.getUid(), talking > 0);

        }

        /**
         * 他人静音
         *
         * @param user
         */
        @Override
        public void onOtherMuted(ChannelUser user) {
            Log.d("qtt_debug", "onOtherMute " + user.getUid() + " " + user.isMuted());
//            updateTalkerMuteOnlyMe(user.getUid(),user.isMuted());
            appendMsg("用户" + user.getUid() + " 静音:" + user.isMuted());
            updateTalkerMute(user.getUid(), user.isMuted(), user);
        }

        /**
         * 他人状态改变（上麦，下麦）
         *
         * @param user
         */
        @Override
        public void onOtherRoleChanged(ChannelUser user) {
            Log.d("qtt_debug", "onOtherRoleChanged " + user.getUid() + ", 角色状态=" + user.getAudioRole());
            appendMsg("用户" + user.getUid() + " 角色:" + user.getAudioRole());
            if (user.getAudioRole() == TALKER) {
//                updateTalkerList(user.getUid(), true, user.isMuted(), "");
                onTalker(user.getUid(), user.isMuted(), -1, user);
                updateAudienceList(user.getUid(), false);
            } else {
//                updateTalkerList(user.getUid(), false, false, "");
                wheatTalker(user.getUid());
                updateAudienceList(user.getUid(), true);
            }
        }

        @Override
        public void onSelfRoleChanged(ChannelRole channelRole) {
            appendMsg("自己角色:" + channelRole);
            Log.d("qtt_debug", "onSelfRoleChanged " + channelRole);
            if (channelRole == ChannelRole.TALKER) {
                mySeatPosition = mySeatPositionTmp;
                onTalker(mUid, false, mySeatPositionTmp, null);
                updateAudienceList(mUid, false);
            } else if (channelRole == ChannelRole.AUDIENCE) {
                mySeatPosition = -1;
                wheatTalker(mUid);
                updateAudienceList(mUid, true);
            }

        }

        @Override
        public void onOtherNetworkStats(ChannelUser channelUser) {
            updateTalkerMute(channelUser.getUid(), channelUser.isMuted(), channelUser);
        }

        @Override
        public void onSelfNetworkStats(int myRtt) {
            Log.d("qtt_debug", "onSelfNetworkStats myRtt:" + myRtt);
            RoomActivity.this.myRtt = myRtt;
            updateNetPopMyRtt(mySeatPosition);
        }
    }


    public void updateNetPopMyRtt(int position) {
        if (micNetworkPopupWindow != null && micNetworkPopupWindow.isShowing()) {
            micNetworkPopupWindow.updateMyRttView(position);
        }
    }

    public void updateNetPop(int position, MicSeatBean micSeatBean) {
        if (micNetworkPopupWindow != null && micNetworkPopupWindow.isShowing()) {
            micNetworkPopupWindow.updateView(position, micSeatBean);
        }
    }


    @OnClick({R.id.iv_back, R.id.iv_setting, R.id.view_colse_setting, R.id.iv_record_file, R.id.iv_music_stop, R.id.iv_music_stop_two})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_back:
                showExitRoomDialog();
                break;
            case R.id.iv_setting:
                //设置
                llSetting.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(RoomActivity.this, R.anim.in_from_right);
                llSetting.startAnimation(animation);
                break;
            case R.id.view_colse_setting:
                Animation animation_out = AnimationUtils.loadAnimation(RoomActivity.this, R.anim.out_from_right);
                llSetting.startAnimation(animation_out);
                animation_out.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        llSetting.post(new Runnable() {
                            @Override
                            public void run() {
                                llSetting.setVisibility(View.GONE);
                            }
                        });
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
                break;
            case R.id.iv_record_file:
                onButtonPlayClicked();
                break;
            case R.id.iv_music_stop:
                onButtonStopClicked();
                break;
            case R.id.iv_music_stop_two:
                onButtonStopClicked();
                break;
        }
    }

    /**
     * 设置音乐播放的view
     */
    public void setMusicSpiner() {
        ArrayAdapter<String> spinnerAdapter = new ArrayAdapter<String>(RoomActivity.this,
                R.layout.item_spiner_room_setting_music, spinnerMusicItems);
        spinnerAdapter.setDropDownViewResource(R.layout.item_spiner_room_setting_music_dropdown);
        spMusic.setAdapter(spinnerAdapter);
        spMusic.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view,
                                       int pos, long id) {
                if (pos == 0) {
                    mp3Player.enableLocalPlay(true);
                    mp3Player.enableRemotePlay(false);
                } else if (pos == 1) {
                    mp3Player.enableRemotePlay(true);
                    mp3Player.enableLocalPlay(false);
                } else if (pos == 2) {
                    mp3Player.enableRemotePlay(true);
                    mp3Player.enableLocalPlay(true);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {
            }
        });
    }


    /**
     * 设置麦位的适配器
     */
    public void setMicGroupView() {
        //获取数据
        if (micSeatDataList == null) {
            micSeatDataList = new ConcurrentHashMap<>();
        }
        micItemAdapter = new MicItemAdapter(RoomActivity.this, micSeatDataList, new MicPopupWindow.PopOnclick() {

            @Override
            public void onClickTakeMic(int position) {
                Log.i(TAG, "上麦");
                audioChannel.changeRole(ChannelRole.TALKER);
                mySeatPositionTmp = position;
            }

            @Override
            public void onClickWheatMic(int position, MicSeatBean micSeatBean) {
                Log.i(TAG, "下麦");
                audioChannel.changeRole(ChannelRole.AUDIENCE);
            }

            @Override
            public void onClickCancelMute(int position, MicSeatBean micSeatBean) {
                Log.i(TAG, "取消静音");
//                updateTalkerList(micSeatBean.getUid(), null, false, "");
                updateTalkerMuteOnlyMe(micSeatBean.getUid(), false);
                audioChannel.mute(micSeatBean.getUid(), false);
            }

            @Override
            public void onClickMute(int position, MicSeatBean micSeatBean) {
                Log.i(TAG, "静音");
//                updateTalkerList(micSeatBean.getUid(), null, true, "");
                updateTalkerMuteOnlyMe(micSeatBean.getUid(), true);
                audioChannel.mute(micSeatBean.getUid(), true);
            }

            @Override
            public void onClickPrivateChat(int position, MicSeatBean micSeatBean) {
//                audioChannel.whisper(micSeatBean.getUid(), true);
//                updatePrevateChat(micSeatBean.getUid(), true);
//                Log.i(TAG, "私聊");
            }

            @Override
            public void onClickCancelPrivate(int position, MicSeatBean micSeatBean) {
//                audioChannel.whisper(micSeatBean.getUid(), false);
//                updatePrevateChat(micSeatBean.getUid(), false);
//                Log.i(TAG, "取消私聊");
            }
        });
        //配置适配器
        gvMicList.setAdapter(micItemAdapter);
    }


    /**
     * 自定义麦位适配器
     */
    public class MicItemAdapter extends BaseAdapter {
        private Context mContext;
        private int count = Config.RoomSeatCount;
        private MicPopupWindow.PopOnclick popOnclick;

        public MicItemAdapter(Context context, Map<Integer, MicSeatBean> seatMap, MicPopupWindow.PopOnclick popOnclick) {
            this.mContext = context;
            this.popOnclick = popOnclick;
        }


        @Override
        public int getCount() {
            return count;
        }

        @Override
        public Object getItem(int position) {
            return micSeatDataList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder = null;

            if (convertView == null) {
                convertView = LayoutInflater.from(mContext).inflate(R.layout.item_room_mic_list, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.iv_mic_img = (ImageView) convertView.findViewById(R.id.iv_mic_img);
                viewHolder.iv_mic_speaking_img = (ImageView) convertView.findViewById(R.id.iv_mic_speaking_img);
                viewHolder.iv_mic_speaking_img_two = (ImageView) convertView.findViewById(R.id.iv_mic_speaking_img_two);
                viewHolder.tv_user_name = (TextView) convertView.findViewById(R.id.tv_user_name);
                viewHolder.iv_mic_state = (ImageView) convertView.findViewById(R.id.iv_mic_state);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            MicSeatBean micSeatBean = null;
            if (micSeatDataList != null && Config.RoomSeatCount > position) {
                micSeatBean = micSeatDataList.get(position);
            }

            if (micSeatBean == null) {
                viewHolder.iv_mic_state.setVisibility(View.GONE);
                viewHolder.tv_user_name.setVisibility(View.INVISIBLE);
                viewHolder.iv_mic_img.setImageResource(R.drawable.layer_room_mic_item_normal);
            } else {
                GlideUtil.loadMicHeadUrl(mContext, viewHolder.iv_mic_img, micSeatBean.getHead_url());
                viewHolder.tv_user_name.setVisibility(View.VISIBLE);
                viewHolder.tv_user_name.setText(micSeatBean.getUsername() != null ? micSeatBean.getUsername() : "");
                setMicStateView(viewHolder.iv_mic_state, micSeatBean);
            }
            setMicSpeaking(viewHolder.iv_mic_speaking_img, viewHolder.iv_mic_speaking_img_two, micSeatBean);
            setOnclick(position, viewHolder, micSeatBean);
            updateNetPop(position, micSeatBean);
            return convertView;
        }

        private void setOnclick(final int position, final ViewHolder viewHolder, final MicSeatBean micSeatBean) {
            viewHolder.iv_mic_img.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (micSeatBean == null && mySeatPosition >= 0) {
                        return;
                    }
                    micNetworkPopupWindow = new MicNetworkPopupWindow(mContext, position, micSeatBean);
                    View contentViewNet = micNetworkPopupWindow.getContentView();
                    //测量view 注意这里，如果没有测量  ，下面的popupHeight高度为-2  ,因为LinearLayout.LayoutParams.WRAP_CONTENT这句自适应造成的
                    contentViewNet.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
                    int popupWidth = contentViewNet.getMeasuredWidth();    //  获取测量后的宽度
                    int popupHeight = contentViewNet.getMeasuredHeight();  //获取测量后的高度
                    int[] location = new int[2];
                    // 获得位置 这里的v是目标控件，就是你要放在这个v的上面还是下面
                    v.getLocationOnScreen(location);
                    //这里就可自定义在上方和下方了 ，这种方式是为了确定在某个位置，某个控件的左边，右边，上边，下边都可以
                    micNetworkPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - popupWidth / 2, location[1] - popupHeight);

                    micPopupWindow = new MicPopupWindow(mContext, position, micSeatBean);
                    micPopupWindow.setPopOnclick(popOnclick);
                    View contentView = micPopupWindow.getContentView();
                    contentView.measure(0, 0);
                    int offsetX = (viewHolder.iv_mic_img.getWidth() - micPopupWindow.getContentView().getMeasuredWidth()) / 2;
                    int offsetY = 0;
                    PopupWindowCompat.showAsDropDown(micPopupWindow, viewHolder.iv_mic_img, offsetX, offsetY, Gravity.START);

                    micPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
                        @Override
                        public void onDismiss() {
                            if (micNetworkPopupWindow != null && micNetworkPopupWindow.isShowing()) {
                                micNetworkPopupWindow.dismiss();
                            }
                        }
                    });

                }
            });


        }

        public void setMicStateView(ImageView imageView, MicSeatBean micSeatBean) {
            Log.i(TAG, "micSeatBean " + micSeatBean.getUsername() + "  isMute:" + micSeatBean.isMute() + "   isOnly_me_mute:" + micSeatBean.isOnly_me_mute());
            if (micSeatBean.isOnly_me_mute()) {
                imageView.setVisibility(View.VISIBLE);
                imageView.setBackgroundResource(R.drawable.shape_room_mic_item_state_bg);
                imageView.setImageResource(R.drawable.layer_room_mic_item_no_voice);
            } else if (micSeatBean.isPrivate_chat()) {
                imageView.setVisibility(View.VISIBLE);
                imageView.setBackgroundResource(R.drawable.shape_room_mic_item_state_two_bg);
                imageView.setImageResource(R.drawable.erke_erlong);
            } else if (micSeatBean.isMute()) {
                imageView.setVisibility(View.VISIBLE);
                imageView.setBackgroundResource(R.drawable.shape_room_mic_item_state_bg);
                imageView.setImageResource(R.drawable.layer_room_mic_item_no_mic);
            } else {
                imageView.setVisibility(View.GONE);
            }
        }

        public void setMicSpeaking(ImageView imageView, final ImageView imageView_two, MicSeatBean micSeatBean) {
            if (micSeatBean != null && micSeatBean.isSpeaking()) {
                imageView.setVisibility(View.VISIBLE);
                Animation animation = AnimationUtils.loadAnimation(mContext, R.anim.anima_room_mic_speaking);
                imageView.startAnimation(animation);
                imageView_two.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        imageView_two.setVisibility(View.VISIBLE);
                        Animation animation_two = AnimationUtils.loadAnimation(mContext, R.anim.anima_room_mic_speaking);
                        imageView_two.startAnimation(animation_two);
                    }
                }, 500);

            } else {
                try {
                    Animation animation = imageView.getAnimation();
                    if (animation != null) {
                        animation.cancel();
                        imageView.clearAnimation();
                    }
                    imageView.setVisibility(View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                try {
                    Animation animation_two = imageView_two.getAnimation();
                    if (animation_two != null) {
                        animation_two.cancel();
                        imageView_two.clearAnimation();
                    }
                    imageView_two.setVisibility(View.GONE);
                } catch (Exception e) {
                    e.printStackTrace();
                }


            }
        }

        public class ViewHolder {
            public ImageView iv_mic_img;
            public ImageView iv_mic_speaking_img;
            public ImageView iv_mic_speaking_img_two;
            public TextView tv_user_name;
            public ImageView iv_mic_state;
        }

    }


}
